package leetcode.hot100;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 15. 三数之和
 *
 * @author: yjf
 * @date: 2024/11/28
 */
public class LeetCode15 {

    public static List<List<Integer>> threeSum1(int[] nums) {
        if (nums == null || nums.length < 3) {
            return new ArrayList<>();
        }
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(nums);
        process(nums, res, new int[3], 0, 0);
        return res;
    }

    public static void process(int[] nums, List<List<Integer>> res, int[] intS, int level, int index) {
        if (level == 3) {
            if (intS[0] + intS[1] + intS[2] == 0) {
                List<Integer> list = new ArrayList<>();
                list.add(intS[0]);
                list.add(intS[1]);
                list.add(intS[2]);
                res.add(list);
            }
            return;
        }
        Integer cur = Integer.MIN_VALUE;
        for (int i = index; i < nums.length; i++) {
            if (!cur.equals(nums[i])) {
                cur = nums[i];
                intS[level] = nums[i];
                process(nums, res, intS, level + 1, i + 1);
            }
        }
    }

    // 双指针
    public static List<List<Integer>> threeSum(int[] nums) {
        if (nums == null || nums.length < 3) {
            return new ArrayList<>();
        }
        Arrays.sort(nums);
        List<List<Integer>> res = new ArrayList<>();
        for (int i = 0; i < nums.length; i++) {
            int k = nums.length - 1;
            int target = -nums[i];
            if (i == 0 || nums[i] != nums[i - 1]) {
                for (int j = i + 1; j < nums.length; j++) {
                    if (j >= k) {
                        break;
                    }
                    if (j == i + 1 || nums[j] != nums[j - 1]) {
                        while (j < k && nums[j] + nums[k] > target) {
                            k--;
                        }
                        if (j == k) {
                            break;
                        }
                        if (nums[j] + nums[k] == target) {
                            res.add(Arrays.asList(nums[i], nums[j], nums[k]));
                        }
                    }
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        System.out.println(threeSum(new int[]{-1, 0, 1, 2, -1, -4}));   // [[-1,-1,2],[-1,0,1]]
    }
}
